/*
 * 文件名：PeaceLawcaseController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wangw
 * 修改时间：2020年3月30日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.PeaceLawcaseDomain;
import top.infopub.mgr.la.service.CarryLawcaseService;
import top.infopub.mgr.la.service.PeaceLawcaseService;
import top.infopub.mgr.la.service.SueLawcaseService;
import top.infopub.mgr.la.service.UpwardLawcaseService;
import top.infopub.mgr.la.vo.CarryLawcaseVo;
import top.infopub.mgr.la.vo.PeaceLawcaseVo;
import top.infopub.mgr.la.vo.SueLawcaseVo;
import top.infopub.mgr.la.vo.UpwardLawcaseVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.CarryLawcase;
import top.infopub.model.la.PeaceLawcaseAtt;
import top.infopub.model.la.SueLawcase;
import top.infopub.model.la.UpwardLawcase;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.Page;


/**
 * 案件调解执行和解
 * @author wangw
 * @version 2020年3月31日
 * @see PeaceLawcaseController
 * @since
 */
@Controller
@RequestMapping("/peaceLawcase")
public class PeaceLawcaseController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private UpwardLawcaseService upwardLawcaseService;
    
    @Autowired
    private SueLawcaseService sueLawcaseService;

    @Autowired
    private PeaceLawcaseService peaceLawcaseService;
    
    @Autowired
    private CarryLawcaseService carryLawcaseService;

    /**
     * 调解案件列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-peaceLawcase-list";
    }

    /**
     * 调解案件列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<PeaceLawcaseDomain> queryDataByCondition(PeaceLawcaseVo peaceLawcaseVo,
                                                        ParamPage paramPage) {
        Page<PeaceLawcaseDomain> page = new Page<PeaceLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (peaceLawcaseVo.getEndDate() != null) {
            peaceLawcaseVo.setEndDate(DateUtils.addDays(peaceLawcaseVo.getEndDate(), 1));
        }
        //查询时，执行申请结束日期增加一天
        if (peaceLawcaseVo.getPeaceEndDate() != null) {
            peaceLawcaseVo.setPeaceEndDate(DateUtils.addDays(peaceLawcaseVo.getPeaceEndDate(), 1));
        }
        page = peaceLawcaseService.selectByDomainWhere(page, peaceLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 调解案件-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<PeaceLawcaseDomain> queryMyCheckDataByCondition(PeaceLawcaseVo peaceLawcaseVo,
                                                               ParamPage paramPage) {
        Page<PeaceLawcaseDomain> page = new Page<PeaceLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (peaceLawcaseVo.getEndDate() != null) {
            peaceLawcaseVo.setEndDate(DateUtils.addDays(peaceLawcaseVo.getEndDate(), 1));
        }
        //查询时，执行申请结束日期增加一天
        if (peaceLawcaseVo.getPeaceEndDate() != null) {
            peaceLawcaseVo.setPeaceEndDate(DateUtils.addDays(peaceLawcaseVo.getPeaceEndDate(), 1));
        }
        peaceLawcaseVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = peaceLawcaseService.selectMyCheckByDomainWhere(page, peaceLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 调解案件-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        return "la/lay-peaceLawcase-add";
    }
    
    /**
     * 根据类型查询对应的案件记录
     * @param type 原申请单类型 01=起诉案件,02=上诉案件,03=调解案件
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLawcaseByType")
    @ResponseBody
    public Map<String, Object> getLawcaseByType(String type) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if(type.equals("01")){
                //查询可执行和解案件的记录
                List<SueLawcase> sueLawcases = sueLawcaseService.selectUsablePeace();
                map.put("lawcases", sueLawcases);
            }else if(type.equals("02")){
                List<UpwardLawcase> upwardLawcases = upwardLawcaseService.selectUsablePeace();
                map.put("lawcases", upwardLawcases);
            }else if(type.equals("03")){
                List<CarryLawcase> carryLawcases = carryLawcaseService.selectUsablePeace();
                map.put("lawcases", carryLawcases);
            }
        }
        catch (Exception e) {
            log.error("根据类型查询案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
    
    /**
     * 根据类型和id查询案件记录
     * @param type 原申请单类型
     * @param lawcaseId 记录id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLawcaseById")
    @ResponseBody
    public Map<String, Object> getLawcaseById(String type,String lawcaseId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if(type.equals("01")){
                //查询调解案件记录
                Map<String, Object> mapWhere = new HashMap<String, Object>();
                mapWhere.put("sueLawcaseId", lawcaseId);
                mapWhere.put("processStatus", "9");
                mapWhere.put("orderCondition", "ADD_TIME desc");
                List<CarryLawcase> carryLawcases = carryLawcaseService.selectByMapWhere(mapWhere);
                if(CollectionUtils.isNotEmpty(carryLawcases)){
                    CarryLawcaseVo carryLawcase = carryLawcaseService.queryById(carryLawcases.get(0).getId());
                    map.put("lawcase", carryLawcase);
                    map.put("attTypes", "1");
                }else{
                    //查询上诉案件记录
                    List<UpwardLawcase> upwardLawcases = upwardLawcaseService.selectByMapWhere(mapWhere);
                    if (CollectionUtils.isNotEmpty(upwardLawcases)) {
                        UpwardLawcaseVo upwardLawcase = upwardLawcaseService.queryById(upwardLawcases.get(0).getId());
                        map.put("lawcase", upwardLawcase);
                        map.put("attTypes", "2");
                    }else {//没有上诉案件记录，则查询起诉案件记录
                        SueLawcaseVo sueLawcase = sueLawcaseService.queryById(lawcaseId);
                        map.put("lawcase", sueLawcase);
                        map.put("attTypes", "1");
                    }
                }
            }else if(type.equals("02")){
                UpwardLawcaseVo upwardLawcase = upwardLawcaseService.queryById(lawcaseId);
                //查询调解案件记录
                Map<String, Object> mapWhere = new HashMap<String, Object>();
                mapWhere.put("sueLawcaseId", upwardLawcase.getSueLawcaseId());
                mapWhere.put("processStatus", "9");
                mapWhere.put("orderCondition", "ADD_TIME desc");
                List<CarryLawcase> carryLawcases = carryLawcaseService.selectByMapWhere(mapWhere);
                if(CollectionUtils.isNotEmpty(carryLawcases)){
                    CarryLawcaseVo carryLawcase = carryLawcaseService.queryById(carryLawcases.get(0).getId());
                    map.put("lawcase", carryLawcase);
                    map.put("attTypes", "1");
                }else{
                    map.put("lawcase", upwardLawcase);
                    map.put("attTypes", "2");
                }
            }else if(type.equals("03")){
                CarryLawcaseVo carryLawcase = carryLawcaseService.queryById(lawcaseId);
                map.put("lawcase", carryLawcase);
                map.put("attTypes", "1");
            }
        }
        catch (Exception e) {
            log.error("根据类型和id查询案件记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询调解案件详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 调解案件Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        PeaceLawcaseVo peaceLawcase = peaceLawcaseService.queryById(id);
        map.put("peaceLawcase", peaceLawcase);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, peaceLawcase.getProcessId());
        return new ModelAndView("la/lay-peaceLawcase-detail", map);
    }

    /**
     * 新增调解案件
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,PeaceLawcaseVo peaceLawcase) {
        String[] fileAtt1 = request.getParameterValues("fileAtt01");
        String[] fileAtt2 = request.getParameterValues("fileAtt02");
        String[] fileAtt3 = request.getParameterValues("fileAtt03");
        String[] fileAtt11 = request.getParameterValues("fileAtt11");
        String[] fileAtt12 = request.getParameterValues("fileAtt12");
        String[] fileAtt13 = request.getParameterValues("fileAtt13");
        if (fileAtt1 == null || fileAtt1.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("生效法律文书未上传");
        }
        if (fileAtt2 == null || fileAtt2.length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("执行申请书未上传");
        }
        //调解案件表处理
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        peaceLawcase.setId(id);
        peaceLawcase.setAddBy(vo.getId());
        peaceLawcase.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_peace_lawcase");
        peaceLawcase.setCodes(code);
        // 处理processId
        peaceLawcase.setProcessId(IdFactory.getUUIDUpper());
        peaceLawcase.setProcessStatus("1");//审批中
        peaceLawcase.setUptBy(vo.getId());
        peaceLawcase.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<PeaceLawcaseAtt> peaceLawcaseAtts = new ArrayList<PeaceLawcaseAtt>();
        //调解/执行和解的理由与方案
        if (fileAtt1 != null) {
            for (String file : fileAtt1) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        //调解协议/执行和解协议
        if (fileAtt2 != null) {
            for (String file : fileAtt2) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        //其他附件
        if (fileAtt3 != null) {
            for (String file : fileAtt3) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        //起诉状
        if (fileAtt11 != null) {
            for (String file : fileAtt11) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        //上诉书
        if (fileAtt12 != null) {
            for (String file : fileAtt12) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        //生效法律文书
        if (fileAtt13 != null) {
            for (String file : fileAtt13) {
                PeaceLawcaseAtt peaceLawcaseAtt = createFileAtt(vo, id, file);
                peaceLawcaseAtts.add(peaceLawcaseAtt);
            }
        }
        peaceLawcaseService.savePeaceLawcase(peaceLawcase, peaceLawcaseAtts);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "法务管理 -调解案件：案件名称=" + peaceLawcase.getLawcaseName(), null);
        return RspVo.getSuccessResponse();
    }

    private PeaceLawcaseAtt createFileAtt(AuthorizationVO vo, String peaceLawcaseId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        PeaceLawcaseAtt fileAtt = new PeaceLawcaseAtt();
        fileAtt.setTypes(fileAttStr[0]);
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setPeaceLawcaseId(peaceLawcaseId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "peaceLawcaseAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
